package design.donkey.auto.ddl.dialect.mysql.handler;

import design.donkey.auto.ddl.model.ColumnMetaModel;
import design.donkey.framework.common.orm.annotation.PrimaryKeyType;
import design.donkey.framework.common.util.CommonUtils;

/**
 * 默认值及自增长设置
 *
 * @since 0.0.1
 * @author zhangjiakung
 */
public class ColumnHandlerForDefaultAutoIncrement implements ColumnHandler {
    @Override
    public String handle(ColumnMetaModel columnMetaModel) {
        // 是否运行为 null
        boolean nullable = !columnMetaModel.isPrimaryKey() || columnMetaModel.isNullable();
        return switch (columnMetaModel.getJdbcType()) {
            case TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT -> {
                if (PrimaryKeyType.JDBC.equals(columnMetaModel.getPrimaryKeyType()) && columnMetaModel.isPrimaryKey()) {
                    yield "AUTO_INCREMENT";
                } else {
                    yield defaultValue(nullable, columnMetaModel);
                }
            }
            case TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT -> null;
            case TIME, DATE, DATETIME, TIMESTAMP -> defaultValue(nullable, columnMetaModel)
                + defaultValueForUpdate(columnMetaModel);
            default -> defaultValue(nullable, columnMetaModel);
        };
    }

    /**
     * 添加时的默认值
     * 
     * @param columnMetaModel 列扩展注解
     * @return 添加时的默认值
     */
    private String defaultValue(boolean nullable, ColumnMetaModel columnMetaModel) {
        String defaultValue = columnMetaModel.getDefaultValue();
        if (CommonUtils.isNotBlank(defaultValue)) {
            String s = "'";
            if (!defaultValue.startsWith(s) || !defaultValue.endsWith(s)) {
                try {
                    return "DEFAULT '" + Long.valueOf(defaultValue) + "'";
                } catch (Exception ignore) {
                    // ignore
                }
                try {
                    return "DEFAULT '" + Double.valueOf(defaultValue) + "'";
                } catch (Exception ignore) {
                    // ignore
                }
            }
            return "DEFAULT " + defaultValue;
        } else {
            return nullable ? "DEFAULT NULL" : "";
        }
    }

    /**
     * 修改时默认值
     *
     * @param columnMetaModel 列扩展注解
     * @return 修改时默认值
     */
    private String defaultValueForUpdate(ColumnMetaModel columnMetaModel) {
        String defaultValueForUpdate = columnMetaModel.getDefaultValueForUpdate();
        if (CommonUtils.isNotBlank(defaultValueForUpdate)) {
            return " ON UPDATE " + defaultValueForUpdate;
        }
        return "";
    }
}
